package com.rrd.hive.udf.sms;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HiveUdfRegexTools {
    public static String hiveUdfRegExReplace(String s, String regex, String replacement) {
        if (s == null || regex == null || replacement == null) {
            return null;
        }
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(s.toString());
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, replacement);
        }
        m.appendTail(sb);

        return sb.toString();
    }

    static String hiveUdfRegexResStrInPos(String input, String pattern, int pos) {
        if(input != null) {
            Pattern p = Pattern.compile(pattern);
            Matcher matcher = p.matcher(input);
            if (matcher.find()) {
                MatchResult matchResult = matcher.toMatchResult();
                return matchResult.group(pos);
            }
        }
        return null;
    }

    static String hiveUdfRegexResultToString(String input, String pattern) {
        if(input != null) {
            Pattern p = Pattern.compile(pattern);
            Matcher matcher = p.matcher(input);
            if (matcher.find()) {
                MatchResult matchResult = matcher.toMatchResult();
//                System.out.println("match count: " + matchResult.groupCount());
                String res = "";
                for (int i = 0; i < matchResult.groupCount(); i++) {
                    if(matchResult.group(i) != null) {
                        res += matchResult.group(i);
                    }
                }
                return res;
            }
        }
        return null;
    }

    static List<String> hiveUdfRegexResultToList(String input, String pattern) {
        if(input != null) {
            Pattern p = Pattern.compile(pattern);
            Matcher matcher = p.matcher(input);
            List<String> res = new LinkedList<>();
            while (matcher.find()) {
                System.out.println(" matcher.group: " + matcher.group(0));
                res.add(matcher.group());
            }
            return res;
        }
        return null;
    }

    public static int hiveUdfRegExpEx(String input, String pattern) {
        if(input != null) {
            Pattern p = Pattern.compile(pattern);
            Matcher matcher = p.matcher(input);
            if (matcher.find(0)) {
                return 1;
            }
        }
        return 0;
    }
}
